package com.yfbao.horizon.schedule.tk.meter;

import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Tags;
import org.springframework.stereotype.Component;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Gauge;

import javax.annotation.PostConstruct;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

@Component
public class LockThreadMetrics {

    private final MeterRegistry meterRegistry;
    private final ThreadMXBean threadMXBean;
    private static DistributionSummary summary;

    public LockThreadMetrics(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
        this.threadMXBean = ManagementFactory.getThreadMXBean();
    }

    @PostConstruct
    public void init() {
        // 注册监控死锁的线程数量
        Gauge.builder("jvm.threads.deadlocked.count", this::getDeadlockedThreadCount)
                .description("Number of threads that are deadlocked")
                .register(meterRegistry);

        // 注册监控阻塞状态的线程数量
        Gauge.builder("jvm.threads.blocked.count", this::getBlockedThreadCount)
                .description("Number of threads that are blocked on locks")
                .register(meterRegistry);
        summary = meterRegistry.summary("test.tt",  Tags.of("test", "tx"));
//        summary = meterRegistry.summary("test", "tt");
//        summary = Summary.build().name("test_tt")
//                .help("sss.").register();
    }

    public static void addSummary(Long value){
        if(summary ==null){
            return;
        }

        if(value !=null){
//            summary.observe(value);
            summary.record(value);
        }
    }

    // 获取死锁线程的数量
    private int getDeadlockedThreadCount() {
        long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
        return deadlockedThreads == null ? 0 : deadlockedThreads.length;
    }

    // 获取被锁阻塞的线程数量
    private int getBlockedThreadCount() {
        long[] threadIds = threadMXBean.getAllThreadIds();
        int blockedCount = 0;
        for (long threadId : threadIds) {
            ThreadInfo threadInfo = threadMXBean.getThreadInfo(threadId);
            if (threadInfo != null && threadInfo.getThreadState() == Thread.State.BLOCKED) {
                blockedCount++;
            }
        }
        return blockedCount;
    }
}
